﻿using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System;

namespace AutoRoot
{		
	public static class XmlSupport 
	{
		public static T DeserializeXml<T> (this string xml) where T : class
		{
			if( xml != null ) {
				XmlSerializer s = new XmlSerializer (typeof(T));
				using (MemoryStream m = new MemoryStream (Encoding.UTF8.GetBytes (xml)))
				{
					return (T)s.Deserialize (m);
				} 
			}
			return null;
		}
		
		public static object DeserializeXml(this string xml, Type tp) 
		{
			XmlSerializer s = new XmlSerializer (tp);
			using (MemoryStream m = new MemoryStream (Encoding.UTF8.GetBytes (xml)))
			{
				return s.Deserialize (m);
			}
		}
		
		public static string SerializeXml (this object item)
		{
			XmlSerializer s = new XmlSerializer (item.GetType ());
			using (MemoryStream m = new MemoryStream())
			{
				s.Serialize (m, item);
				m.Flush ();
				return Encoding.UTF8.GetString (m.GetBuffer ());
			}			
		}		
	}
}